package com.samba.admin;

import java.util.Collection;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import com.samba.entites.Category;
import com.samba.sessions.AdminServiceDAO;

@ManagedBean(name="categoryManager")
@SessionScoped
public class CategoryManagerBean {
	
	@EJB()
	private AdminServiceDAO adminService;
	
	private Category managed;
	
	/**
	 * create a new instance of CagegoryManagerBean
	 */
	
	public CategoryManagerBean()
	{
		managed = new Category();
	}
	
	public void initCategoryFromRequestParam()
	{ 
		managed = adminService.findCategoryById(getManagedCategoryId());
	}
	public int getManagedCategoryId()
	{
		ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ec.getRequest();
		String param = request.getParameter("id");
		return Integer.parseInt(param);
	}
	
	/**
	 * retourne les elements de la bd
	 * 
	 */
	public Collection getList()
	{
		return adminService.findAllCategories();
	}
	
	public void detial()
	{
	}
	public void remove()
	{
		adminService.deleteCategory(getManagedCategoryId());
	}
	public void edit()
	{
		initCategoryFromRequestParam();
	}
	public void newBlank()
	{
		managed = new Category();
	}
	public void save()
	{
		if(managed.getId() > 0)
		{
			adminService.addCategory(managed);
			newBlank();
		}
	}
	public Category getManaged()
	{
		return managed;
	}
	
	public void setManaged(Category managedCategory)
	{
		this.managed  = managedCategory;
	}
}
